<?php

namespace WenRuns\Laravel\Admin\Form\Field\Grid\Field;

use WenRuns\Laravel\Admin\Form\Field\Grid\Column;
use WenRuns\Laravel\Admin\Form\Field\Grid\Grid;
use WenRuns\Laravel\Admin\Form\Field\Grid\Field\Number;

/**
 * @method Input input($column, $label = '')
 * @method Select select($column, $label = '')
 * @method Number number($column, $label = '')
 * @method Textarea textarea($column, $label = '')
 * @method Radio radio($column, $label = '')
 * @method Checkbox checkbox($column, $label = '')
 * @method Expand expand($column, $label, $content)
 * @method Modal modal($column, $label = '', $content = null, $title = '')
 * @method Color color($column, $label = '')
 * @method Decimal decimal($column, $label = '')
 * @method Display display($column, $label = '')
 * @method Hidden hidden($column, $label = '')
 * @method Time time($column, $label = '')
 * @method Date date($column, $label = '')
 * @method DateTime datetime($column, $label = '')
 * @method PowerSwitch switch ($column, $label = '')
 * @method Image image($column, $label = '')
 * @method Html html($label, $html)
 * @method Group group($label, \Closure $closure)
 * @method Email email($column, $label)
 * @method Phone phone($column, $label)
 * @method Password password($column, $label)
 * @method Range range($column, $label)
 * @method Tab tab(\Closure $closure)
 */
class Group extends Column
{
    protected $type = 'group';

    /**
     * @var array
     */
    protected $columns = [];

    /**
     * @var int|mixed
     */
    protected $level;

    /**
     * @var int
     */
    protected $colspan = 1;

    protected $parent;

    /**
     * @param Grid $grid
     * @param $label
     * @param \Closure $closure
     */
    public function __construct(Grid $grid, $label, \Closure $closure, $level = 0, Group $parent = null)
    {
        $this->level = $level;
        $this->parent = $parent;
        parent::__construct($grid, null, $label);
        call_user_func($closure, $this);
        if ($level > 0) {
            $num = count(array_filter($this->columns, function ($item) {
                return $item->type != 'hidden';
            }));
            if ($num > 0) {
                if ($grid->headerRow < $level) {
                    $grid->headerRow = $level;
                }
                $this->colspan += $num - 1;
                if ($parent) {
                    $parent->setColspan($num);
                }
            }
        }

    }

    public function setColspan($col)
    {
        $this->colspan += $col - 1;

        if ($this->parent) {
            $this->parent->setColspan($this->colspan);
        }
        return $this;
    }

//    /**
//     * 子级grid
//     * @param $column
//     * @param \Closure $closure
//     * @param $label
//     * @return Grid
//     */
//    public function grid($column, \Closure $closure, $label = '')
//    {
//        $grid = new Grid($column, [$closure, $label], $this);
//        $this->columns[] = $grid;
//        call_user_func($closure, $grid);
//        return $grid;
//    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws \Exception
     */
    public function __call($name, $arguments)
    {
        return Grid::checkColumn($name, $arguments, function ($column, $parameters) use ($name) {
            if ($name == 'group' && $this->level > 0) {
                $parameters[] = $this->level + 1;
                $parameters[] = $this;
            }
            $instance = new $column($this->grid, ...$parameters);
            $this->columns[] = $instance;
            return $instance;
        });
    }

    /**
     * @return array
     */
    public function render()
    {
        $res = parent::render();
        $res['level'] = $this->level;
        $res['colspan'] = $this->colspan;
        $res['children'] = $this->children();
        return $res;
    }

    /**
     * 下级字段
     * @return array
     */
    protected function children()
    {
        $columns = [];
        foreach ($this->columns as $column) {
            /** @var Column $column */
            if ($column instanceof Grid) {
                $columns[] = [
                    'label' => $column->label(),
                    'type' => 'grid',
                    'name' => $column->column(),
                    'children' => $column->initOption(1),
                ];
            } else {
                $columns[] = $column->render();
            }
        }
        return $columns;
    }

    /**
     * 获取值
     * @return mixed|null
     */
    public function getValue()
    {
        $value = empty($this->row) ? $this->default : $this->row;
        if (!empty($value)) {
            foreach ($this->columns as $column) {
                /** @var Column $column */
                if ($column instanceof Grid) {
                    $subValue = $value[$column->column()] ?? null;
                    if (!empty($subValue)) {
                        $column->value($subValue);
                    }
                    $value[$column->column()] = $column->initOption(2);
                } else if ($column instanceof Group) {
                    $value = $column->setRow($value)->getValue();
                } else if (
                    $column->getName() &&
                    (
                        $column->withClosure instanceof \Closure ||
                        $column instanceof Expand ||
                        $column instanceof Modal
                    )
                ) {
//                    try {
                        $value[$column->getName()] = $column->setRow($value)->getValue();
//                    } catch (\Throwable $e) {
//                        dd($e, $value, $column);
//                    }
                }
            }
        }
        return $value;
    }

    public function columnWidth($width = 6)
    {
        return $this->config('columnWidth', $width);
    }
}
